package com.example.sakurasay.passwordbook

import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.PaddingValues
import androidx.compose.foundation.layout.Row
import androidx.compose.foundation.layout.Spacer
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.height
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.layout.size
import androidx.compose.foundation.lazy.LazyColumn
import androidx.compose.foundation.lazy.items
import androidx.compose.foundation.shape.RoundedCornerShape
import androidx.compose.foundation.clickable
import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.filled.Add
import androidx.compose.material.icons.filled.MoreVert
import androidx.compose.material.icons.outlined.Key
import androidx.compose.material.icons.outlined.Share
import androidx.compose.material3.AlertDialog
import androidx.compose.material3.Button
import androidx.compose.material3.Card
import androidx.compose.material3.CardDefaults
import androidx.compose.material3.ExperimentalMaterial3Api
import androidx.compose.material3.FloatingActionButton
import androidx.compose.material3.Icon
import androidx.compose.material3.IconButton
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.SegmentedButton
import androidx.compose.material3.SegmentedButtonDefaults
import androidx.compose.material3.SingleChoiceSegmentedButtonRow
import androidx.compose.material3.Text
import androidx.compose.material3.TextButton
import androidx.compose.material3.TextField
import androidx.compose.material3.ModalBottomSheet
import androidx.compose.material3.rememberModalBottomSheetState
import androidx.compose.runtime.Composable
import androidx.compose.runtime.collectAsState
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember
import androidx.compose.runtime.setValue
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.platform.LocalContext
import androidx.compose.ui.unit.dp
import androidx.lifecycle.viewmodel.compose.viewModel
import androidx.navigation.NavController
import com.example.sakurasay.passwordbook.data.entities.IndependentPasswordEntry
import com.example.sakurasay.passwordbook.data.entities.SharedPassword
import com.example.sakurasay.passwordbook.data.relations.SharedPasswordWithAccounts
import com.example.sakurasay.passwordbook.viewmodels.PasswordBookViewModel
import com.example.sakurasay.passwordbook.viewmodels.PasswordBookViewModelFactory
import com.example.sakurasay.viewmodels.SettingsViewModel


@OptIn(ExperimentalMaterial3Api::class)
@Composable
fun PasswordBookScreen(
    navController: NavController,
    passwordBookViewModel: PasswordBookViewModel = viewModel(
        factory = PasswordBookViewModelFactory(LocalContext.current.applicationContext as android.app.Application)
    ),
    settingsViewModel: SettingsViewModel = viewModel()
) {
    val selectedModeIndex by passwordBookViewModel.passwordBookMode.collectAsState(initial = 0)
    val isSessionAuthenticated by passwordBookViewModel.isSessionAuthenticated.collectAsState()
    val settingsUiState by settingsViewModel.uiState.collectAsState()
    var showAddSheet by remember { mutableStateOf(false) }

    val modes = listOf("独立密码", "共享密码")
    val independentPasswords by passwordBookViewModel.allIndependentPasswords.collectAsState(initial = emptyList())
    val sharedPasswordsWithAccounts by passwordBookViewModel.sharedPasswordsWithAccounts.collectAsState(initial = emptyList())

    Box(modifier = Modifier.fillMaxSize()) {
        Column {
            SingleChoiceSegmentedButtonRow(
                modifier = Modifier
                    .fillMaxWidth()
                    .padding(horizontal = 16.dp, vertical = 8.dp)
            ) {
                modes.forEachIndexed { index, label ->
                    SegmentedButton(
                        shape = SegmentedButtonDefaults.itemShape(index = index, count = modes.size),
                        onClick = { passwordBookViewModel.setPasswordBookMode(index) },
                        selected = index == selectedModeIndex
                    ) {
                        Text(label)
                    }
                }
            }

            if (selectedModeIndex == 0) {
                IndependentPasswordList(
                    passwords = independentPasswords,
                    onPasswordClick = { /* No action on click */ }
                )
            } else {
                SharedPasswordList(
                    passwords = sharedPasswordsWithAccounts,
                    onPasswordClick = { /* No action on click */ }
                )
            }
        }

        FloatingActionButton(
            onClick = { showAddSheet = true },
            modifier = Modifier
                .align(Alignment.BottomEnd)
                .padding(16.dp),
            containerColor = MaterialTheme.colorScheme.secondary
        ) {
            Icon(Icons.Default.Add, contentDescription = "Add", tint = MaterialTheme.colorScheme.onSecondary)
        }

        if (showAddSheet) {
            AddPasswordBottomSheet(
                isSharedMode = selectedModeIndex == 1,
                onDismiss = { showAddSheet = false },
                onSave = { accountName, username, password, notes ->
                    if (selectedModeIndex == 0) {
                        val newPassword = IndependentPasswordEntry(
                            accountName = accountName,
                            username = username,
                            password = password,
                            website = "", // website is not in the simple form
                            notes = notes,
                            creationDate = System.currentTimeMillis()
                        )
                        passwordBookViewModel.insertIndependentPassword(newPassword)
                    } else {
                        val newSharedPassword = SharedPassword(
                            passwordName = accountName,
                            password = password, // Corrected parameter name
                            notes = notes
                        )
                        // For now, we pass an empty list of accounts.
                        // A more complex UI would be needed to add accounts.
                        passwordBookViewModel.insertSharedPassword(newSharedPassword, emptyList())
                    }
                    showAddSheet = false
                }
            )
        }
    }
}

@OptIn(ExperimentalMaterial3Api::class)
@Composable
fun AddPasswordBottomSheet(
    isSharedMode: Boolean,
    onDismiss: () -> Unit,
    onSave: (String, String, String, String) -> Unit
) {
    val sheetState = rememberModalBottomSheetState()
    var accountName by remember { mutableStateOf("") }
    var username by remember { mutableStateOf("") }
    var password by remember { mutableStateOf("") }
    var notes by remember { mutableStateOf("") }

    ModalBottomSheet(
        onDismissRequest = onDismiss,
        sheetState = sheetState
    ) {
        Column(modifier = Modifier.padding(16.dp)) {
            Text(
                text = if (isSharedMode) "添加共享密码" else "添加独立密码",
                style = MaterialTheme.typography.headlineSmall,
                modifier = Modifier.padding(bottom = 16.dp)
            )
            TextField(
                value = accountName,
                onValueChange = { accountName = it },
                label = { Text("账户名称") },
                modifier = Modifier.fillMaxWidth()
            )
            Spacer(modifier = Modifier.height(8.dp))
            TextField(
                value = username,
                onValueChange = { username = it },
                label = { Text("用户名/账号") },
                modifier = Modifier.fillMaxWidth()
            )
            Spacer(modifier = Modifier.height(8.dp))
            TextField(
                value = password,
                onValueChange = { password = it },
                label = { Text("密码") },
                modifier = Modifier.fillMaxWidth()
            )
            Spacer(modifier = Modifier.height(8.dp))
            TextField(
                value = notes,
                onValueChange = { notes = it },
                label = { Text("备注") },
                modifier = Modifier.fillMaxWidth()
            )
            Spacer(modifier = Modifier.height(16.dp))
            Button(
                onClick = { onSave(accountName, username, password, notes) },
                modifier = Modifier.fillMaxWidth()
            ) {
                Text("保存")
            }
        }
    }
}

@Composable
fun IndependentPasswordList(passwords: List<IndependentPasswordEntry>, onPasswordClick: () -> Unit) {
    LazyColumn(
        contentPadding = PaddingValues(horizontal = 16.dp, vertical = 8.dp),
        verticalArrangement = Arrangement.spacedBy(12.dp)
    ) {
        items(passwords) { password ->
            PasswordListItem(password = password, onItemClick = onPasswordClick)
        }
    }
}

@Composable
fun SharedPasswordList(passwords: List<SharedPasswordWithAccounts>, onPasswordClick: () -> Unit) {
    LazyColumn(
        contentPadding = PaddingValues(horizontal = 16.dp, vertical = 8.dp),
        verticalArrangement = Arrangement.spacedBy(12.dp)
    ) {
        items(passwords) { passwordWithAccounts ->
            PasswordListItem(
                password = IndependentPasswordEntry(
                    id = passwordWithAccounts.sharedPassword.id,
                    accountName = passwordWithAccounts.sharedPassword.passwordName,
                    username = "关联账户: ${passwordWithAccounts.accounts.size}个",
                    password = "", // Not needed for list item
                    website = null,
                    notes = null,
                    creationDate = 0L
                ),
                isShared = true,
                onItemClick = onPasswordClick
            )
        }
    }
}

@Composable
fun PasswordListItem(
    password: IndependentPasswordEntry,
    isShared: Boolean = false,
    onItemClick: () -> Unit
) {
    Card(
        modifier = Modifier
            .fillMaxWidth()
            .clickable(onClick = onItemClick),
        shape = RoundedCornerShape(16.dp),
        colors = CardDefaults.cardColors(
            containerColor = MaterialTheme.colorScheme.surfaceVariant,
        ),
        elevation = CardDefaults.cardElevation(defaultElevation = 4.dp)
    ) {
        Row(
            modifier = Modifier.padding(16.dp),
            verticalAlignment = Alignment.CenterVertically
        ) {
            Icon(
                imageVector = if (isShared) Icons.Outlined.Share else Icons.Outlined.Key,
                contentDescription = if (isShared) "Shared Password" else "Independent Password",
                modifier = Modifier.size(40.dp),
                tint = MaterialTheme.colorScheme.secondary
            )
            Spacer(modifier = Modifier.size(16.dp))
            Column(modifier = Modifier.weight(1f)) {
                Text(
                    text = password.accountName,
                    style = MaterialTheme.typography.titleMedium,
                    color = MaterialTheme.colorScheme.onSurface
                )
                Text(
                    text = password.username,
                    style = MaterialTheme.typography.bodyMedium,
                    color = MaterialTheme.colorScheme.onSurfaceVariant
                )
            }
            IconButton(onClick = { /* TODO: More actions */ }) {
                Icon(
                    Icons.Default.MoreVert,
                    contentDescription = "More options",
                    tint = MaterialTheme.colorScheme.onSurfaceVariant
                )
            }
        }
    }
}